package com.tyut.homework.service.impl;

import com.tyut.homework.dto.*;
import com.tyut.homework.pojo.Dormitory;
import com.tyut.homework.pojo.StuDor;
import com.tyut.homework.pojo.Student;
import com.tyut.homework.repository.DormitoryRepository;
import com.tyut.homework.repository.StuDorRepository;
import com.tyut.homework.service.DormitoryService;
import com.tyut.homework.service.StudentService;
import org.hibernate.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DormitoryServiceImpl implements DormitoryService {

    @Autowired
    private DormitoryRepository dormitoryRepository;
    @Override
    public Dormitory save(Dormitory dormitory) {
        return dormitoryRepository.save(dormitory);
    }
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StuDorRepository stuDorRepository;

    @Override
    public int delete(Integer id) {
        Dormitory dormitory = new Dormitory();
        dormitory.setAptId(id);
        dormitoryRepository.delete(dormitory);
        return 1;
    }

    @Override
    public int update(Dormitory dormitory) {
        dormitoryRepository.saveAndFlush(dormitory);
        return 1;
    }

    @Override
    public Dormitory find(Integer id) {
        return dormitoryRepository.findById(id).get();
    }

    @Override
    public List<Dormitory> findAll() {
        return null;
    }

    @Override
    public Page<Dormitory> getPage(Integer pageNum, Integer pageLimit) {
        Sort sort = new Sort(Sort.Direction.ASC);
        Pageable pageable = new PageRequest(pageNum, pageLimit, sort);
        return dormitoryRepository.findAll(pageable);
    }

    @Override
    public void getDors(Integer apartsNum) {
        //循环遍历所有宿舍并加入表。
        List<Dormitory> list = new ArrayList<>();
        int count = 0;
        for (int i = 1; i<= apartsNum; i++){
            for (int j = 1; j<=5; j++){
                for ( int k= 1; k<=18 ; k++){
                    count++;
                    Dormitory dormitory = new Dormitory();
                    dormitory.setAptId(i);
                    String dor = String.valueOf(k<10? "0"+k :k);
                    dormitory.setDorNum(j+dor);
                    System.out.println(dormitory);
                    list.add(dormitory);
                    if (count % 90 == 0){
                        dormitoryRepository.saveAll(list);
                        list.clear();
                    }
                }
            }
        }
    }

    @Override
    public List<ClazzPeopleNum> getAllClazzPeopleNum(String sex) {
        Query nativeQuery = entityManager.createNativeQuery("select clazz, count(sex) as counts from student where sex=? and status=0 group by clazz");
        List resultList = nativeQuery.setParameter(1, sex).getResultList();
        List<ClazzPeopleNum> clazzPeopleNums = new ArrayList<>();
        for (Object o:resultList){
            Object [] rowArray = (Object[]) o;
            ClazzPeopleNum peopleNum = new ClazzPeopleNum();
            peopleNum.setClazz((String) rowArray[0]);
            peopleNum.setCount(Integer.valueOf(rowArray[1].toString()));
            clazzPeopleNums.add(peopleNum);
        }
        return clazzPeopleNums;

    }

    @Override
    @Transactional
    public void autoMatch() {
        System.out.println("===========");
        // 获取到 班级和人数 信息
        List<ClazzPeopleNum> manList = getAllClazzPeopleNum("男");
        manList.forEach(System.out::println);
        // 计算每个班 男生 要分多少个宿舍
        List<DorscountClazz> list = new ArrayList<>();
        for (int i = 0; i< manList.size(); i++){
            int tempCount = manList.get(i).getCount();
            DorscountClazz dorscountClazz = new DorscountClazz(tempCount%4==0?tempCount/4:tempCount/4+1,
                    manList.get(i).getClazz());
            list.add(dorscountClazz);
        }
        // 拿到了班级和人数， 开始分配:
        // 还要拿到所有未分配的宿舍号列表
        List<Dormitory> notMatch = selectAllNotMatch();
        boolean flag = true;
        list.forEach(System.out::println);
        notMatch.forEach(System.out::println);
        int count = 0;
        int stuCount = 0;
        for (int i= 0; i< notMatch.size(); i++){
            if (!flag){
                break;
            }
            for (int j = 0; j< list.size(); j++){
                if (j == list.size()-1){
                    flag =false;
                }
                for (int k = 0;k< list.get(j).getDorcount(); k++){
                    Dormitory dormitory = new Dormitory();
//                    dormitory.setAptId(notMatch.get(i).getAptId());
                    dormitory.setClazz(list.get(j).getClazz());
                    System.out.println(dormitory.getClazz());
//                    dormitory.setDorNum(notMatch.get(i).getDorNum());
                    dormitory.setId(notMatch.get(count).getId());
                    updateClazz(dormitory);
                    // 更新状态
//                    updateStatus(notMatch.get(count).getId());
//                    studentService.updateStatus(list.get(j).getId());
                    count++;

                }
            }
        }
    }

    public  void autoMatchStudent(){
//                     // 拿到未分配学生列表， 4个为一组分配
//                    List<Student> listNotMatch = studentService.getListNotMatch();
//                    for (int t = 0; t< 4; t++){
//                        if (null == listNotMatch.get(stuCount + 1) || listNotMatch.size()==count-2){
//                            // 如果 下一个是空，则和上一个比较，如果相同则同宿舍
////                            if (!listNotMatch.get(stuCount).getClazz().equals(listNotMatch.get(stuCount - 1).getClazz())){
//                                break;
////                            }
//                        }
//                        if (!listNotMatch.get(stuCount).getClazz().equals(listNotMatch.get(stuCount + 1).getClazz())){
//                            break;
//                        }else {
//                            // 添加数据
//                            StuDor stuDor = new StuDor();
//                            stuDor.setStuId(listNotMatch.get(stuCount).getId());
//                            stuDor.setAptId(notMatch.get(count).getAptId());
//                            stuDor.setDorId(notMatch.get(count).getId());
//                            stuDorRepository.save(stuDor);
//                            //修改状态
//                            studentService.updateStatus(listNotMatch.get(stuCount).getId());
//                            stuCount++;
//                        }
//                    }
    }
    @Override
    public List<Dormitory> selectAllNotMatch() {
        List<Dormitory> list = dormitoryRepository.selectAllNotMatch();
        return list;
    }

    @Override
    public int updateStatus(Integer id) {
        return dormitoryRepository.updateStatus(id);
    }

    @Override
    public void updateClazz(Dormitory dormitory) {
        System.out.println(dormitory.toString());
        dormitoryRepository.updateClazz(dormitory.getClazz(),dormitory.getId());
    }

    @Override
    public List<DorStatus> getDOrsStatus() {
        Query nativeQuery = entityManager.createNativeQuery("select sd.apt_id,d.dor_num,d.clazz,count(sd.dor_id) as peoples from stu_dor sd, dormitory d where sd.dor_id=d.id group by dor_id;");
        List resultList = nativeQuery.getResultList();
        List<DorStatus> list = new ArrayList<>();
        for (Object o:resultList){
            Object [] rowArray = (Object[]) o;
            DorStatus dorStatus = new DorStatus();
            // 第一列是 aptId
            dorStatus.setAptId(((Integer) rowArray[0]));
            // 第二列是 dorNum
            dorStatus.setDorNum((String) rowArray[1]);
            // 第三列是clazz
            dorStatus.setClazz(String.valueOf(rowArray[2]));
            System.out.println("class=========="+dorStatus.getClazz());
            // 第四列是 人数
            dorStatus.setPeoples(Integer.valueOf(rowArray[3].toString()));
            if (dorStatus.getClazz() == null|| dorStatus.getClazz().equals("") || StringUtils.isEmpty(dorStatus.getClazz())){
                list.add(dorStatus);
                break;
            }
            Student student = studentService.findInfoByClazz(dorStatus.getClazz());
            System.out.println(student.toString());
            dorStatus.setDepartment(student.getDepartment());
            dorStatus.setGrade(student.getGrade());
            dorStatus.setSex(student.getSex());
            list.add(dorStatus);
        }
        return list;
    }

    @Override
    public List<DormitoryDTO> findByClazz(String clazz) {
//        return dormitoryRepository.findAllByClazz(clazz);
        Query nativeQuery = entityManager.createNativeQuery("select sd.apt_id,d.id as dor_id,d.clazz,count(sd.dor_id) as peoples,d.dor_num from stu_dor sd, dormitory d where sd.dor_id=d.id and clazz=?1 group by dor_id");
        nativeQuery.setParameter(1, clazz);
        List resultList = nativeQuery.getResultList();
        List<DormitoryDTO> list = new ArrayList<>();
        for (Object o:resultList ){
            Object [] rowArray = (Object[]) o;
            DormitoryDTO dto = new DormitoryDTO();
            dto.setAptId((Integer) rowArray[0]);
            dto.setDorId((Integer) rowArray[1]);
            dto.setClazz((String) rowArray[2]);
            dto.setPeoples(Integer.valueOf(rowArray[3].toString()));
            dto.setDorNum((String) rowArray[4]);
            list.add(dto);
        }
        return list;
    }

    @Override
    public void insertInDor(Integer stuId, Integer aptId, Integer dorId) {
        StuDor stuDor = new StuDor();
        stuDor.setAptId(aptId);
        stuDor.setDorId(dorId);
        stuDor.setStuId(stuId);
        stuDorRepository.save(stuDor);
    }

}
